package agent.behaviours;

import features.Log;
import gui.OrderListActivity;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.widget.Toast;

import com.mechanic.androidexpert.R;
import communication.Message;
import communication.MessageType;
import communication.Order;

public class ReceiveMessagesBehaviour extends CyclicBehaviour {

	OrderListActivity activity;
	int notificationId = 001;

	public ReceiveMessagesBehaviour(OrderListActivity activity) {
		this.activity = activity;
	}

	@Override
	public void action() {
		ACLMessage msg = myAgent.receive();
		if (msg != null) {

			try {
				Log.logp(myAgent, "message received");
				Message msgMessage = (Message) msg.getContentObject();

				if (msgMessage.getType() == MessageType.ORDER) {
					Log.logp(myAgent, "type = ORDER");
					activity.addOrder(msgMessage);
					makeNotification(msgMessage);
				}

			} catch (UnreadableException e) {
				Toast.makeText(activity,
						"Oops! Soemthing goes wrong during receiving message.",
						Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}

		} else
			block();
	}

	public void setActivity(OrderListActivity activity) {
		this.activity = activity;
	}

	private void makeNotification(Message msgMessage) {
		
		Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		String title = ((Order)msgMessage).getTitle();
		String text = ((Order)msgMessage).getLocation().getLatitude()+ " - "+((Order)msgMessage).getLocation().getLongitude();

		NotificationCompat.Builder builder = new Builder(activity)
				.setSmallIcon(R.drawable.order_notification).setContentTitle(title)
				.setContentText(text).setSound(uri).setAutoCancel(true);
		
		Intent resultIntent = new Intent(activity, OrderListActivity.class);
		PendingIntent resultPendingIntent =
		    PendingIntent.getActivity(
		    activity,
		    0,
		    resultIntent,
		    PendingIntent.FLAG_UPDATE_CURRENT
		);
		
		builder.setContentIntent(resultPendingIntent);
		
		
		NotificationManager notificationMgr = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationMgr.notify(notificationId, builder.build());
		
		notificationId++;

	}

}
